#include "Wakeup.h"
#include "RingBuffer.h"
#include "Codec.h"
#include "Model.h"

typedef float LAYERBUFFER[HDRCNT*BUFLEN];

LAYERBUFFER * m_LayerBuffer;

static short * m_WavInput = 0;
static float * m_NetInput = 0;

void WakeupInit(void)
{
	m_LayerBuffer = (LAYERBUFFER*)MALLOC(sizeof(LAYERBUFFER)*2);
	memset(m_LayerBuffer, 0, sizeof(LAYERBUFFER)*2);
	m_WavInput = (short*)m_LayerBuffer[0];
	m_NetInput = m_LayerBuffer[1];

	RingBufferInit();
	CodecInit();
	ModelInit();
}

void WakeupRelease(void)
{
	if(m_LayerBuffer)
	{
		FREE(m_LayerBuffer);
		m_LayerBuffer = 0;
	}

	m_WavInput = 0;
	m_NetInput = 0;

	RingBufferRelease();
	CodecRelease();
	ModelRelease();
}

short gWaveData[BUFLEN*HDRCNT];

float OnWaveData(short* data, int len/* = BUFLEN*/)	//return -1.0=null; others=hisiri confidence; 
{
	//assert(len == BUFLEN);
	static int chunks = 0;

	if(m_LayerBuffer == 0)
		return -1.0f;

	RingBufferSetWaveData(data, len);
	chunks++;

	if((chunks % 4) == 0)
	{
		RingBufferGetWaveData(m_WavInput);
		if(Encode(m_WavInput, m_NetInput))
		{
			float out;
			float ret;
			Forward(m_NetInput, &out);
			ret = Decode(&out);
			if(ret > 0.5f)
			{
				RingBufferGetWaveData(gWaveData);
				RingBufferClear();
			}
			return ret;
		}
	}

	return -1.0f;
}

float OnFileData(short* data, int len/* = HDRCNT*BUFLEN*/)	//return -1.0=null; others=hisiri confidence; 
{
	if(m_LayerBuffer == 0)
		return -1.0f;

	//assert(len == HDRCNT*BUFLEN);

	if(Encode(data, m_NetInput))
	{
		float out;
		Forward(m_NetInput, &out);
		return Decode(&out);
	}

	return -1.0f;
}
